# 标签版本
VERSION := v1.0.0.12


# tekton 配置文件
PIPELINE_FILE = pipelineRun/clone-build-push-run.yaml
KUSTOMIZE_OVERLAY ?= .
CICD_NS ?= cicd


.PHONY: help run-pipeline
.PHONY: install-tekton deploy-workloads install-all apply-cicd

# 显示帮助信息
help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@echo "  help          显示此帮助信息"
	@echo "  run-pipeline  运行Tekton流水线"
	@echo "  apply-cicd    通过Kustomize应用到 cicd 命名空间（默认使用仓库根）"

# 运行Tekton流水线
run-pipeline:
	@echo "Creating PipelineRun from $(PIPELINE_FILE)"
	@PIPELINE_RUN=$$(kubectl create -f $(PIPELINE_FILE) -o name | cut -d'/' -f2); \
	echo "PipelineRun created: $$PIPELINE_RUN"; \
	tkn pipelinerun logs $$PIPELINE_RUN -f


# 一键安装 Tekton 组件
install-tekton:
	@echo "Applying Tekton core components (Pipelines/Triggers/Interceptors/Dashboard)"
	kubectl apply -f install/tekton-pipelines.yaml
	kubectl apply -f install/tekton-triggers.yaml
	kubectl apply -f install/tekton-interceptors.yaml
	kubectl apply -f install/tekton-dashboard.yaml
	@if [ -f install/tekton-ingress.yaml ]; then \
	  echo "Applying Tekton ingress"; \
	  kubectl apply -f install/tekton-ingress.yaml; \
	fi

# 将项目工作负载部署到指定命名空间（默认 cicd）
deploy-workloads:
	@CICD_NS=$${CICD_NS:-cicd}; \
	 echo "Deploy workloads into namespace '$$CICD_NS'"; \
	 kubectl get ns $$CICD_NS >/dev/null 2>&1 || kubectl create ns $$CICD_NS; \
	 kubectl apply -R -f rbac -n $$CICD_NS; \
	 kubectl apply -R -f secret -n $$CICD_NS; \
	 kubectl apply -R -f task -n $$CICD_NS; \
	 kubectl apply -R -f pipeline -n $$CICD_NS; \
	 kubectl apply -R -f triggerbinding -n $$CICD_NS || true; \
	 kubectl apply -R -f triggertemplate -n $$CICD_NS || true; \
	 kubectl apply -R -f listener -n $$CICD_NS || true; \
	 kubectl apply -R -f pipelineRun -n $$CICD_NS || true; \
	 if [ -f ingress/ingress-with-cert.yaml ]; then kubectl apply -f ingress/ingress-with-cert.yaml; fi

# 一次性执行（Tekton + 工作负载）
install-all:
	@scripts/apply-all.sh $${CICD_NS:-cicd}

# 通过 Kustomize overlay 一键应用到 cicd 命名空间
apply-cicd:
	@echo "Ensuring namespace '$(CICD_NS)' exists..."
	@kubectl get ns $(CICD_NS) >/dev/null 2>&1 || kubectl create ns $(CICD_NS)
	@echo "Applying Kustomize from: $(KUSTOMIZE_OVERLAY)"
	kubectl apply -k $(KUSTOMIZE_OVERLAY)


# 默认目标
.DEFAULT_GOAL := help